###############################################
#
#Compute the neighbors productivity excluding the work with 
#i and discounting the work between the neighbors
#IMPORTANT: -DATA NEED TO BE SET BEFORE RUNNING THE FUNCTION
#- NAME THIS DATA SET AS "y"
#- This function is much faster than the one in "netprod.R"
# Author: Lorenzo Ductor
# First Version: 29/04/2015
#
################################################

netprodg<-function(indi,g,y,endyear){
  nei1 <- V(g)[nei(indi)]
  lnei1 <- sapply(nei1, function(v) list(subset(y,
                           auth2==v|auth1==v|auth3==v|auth4==v|auth5==v|auth6==v|auth7==v)) )
authm<-as.data.frame(do.call("rbind",lnei1))
authmu<-unique(authm)
auth    <- c(2,5,8,11,14,17,20)   # column numbers of months
gender         <- c(3,6,9,12,15,18,21)   # column numbers of Fn
myear<-c(4,7,10,13,16,19,22)
authmul <- reshape(authmu,
             times=colnames(authmu)[auth],
             varying=list(auth,gender,myear),
             v.names=c("auth","gender","myear"),
             direction="long")
authmulx=authmul[,c(1,6,8,9,10)]
authmulx=authmulx[!duplicated(authmulx), ]
lnei1b <- sapply(nei1, function(v) list(subset(authmulx, auth==v)) )
authmb<-as.data.frame(do.call("rbind",lnei1b))
authmub<-unique(authmb)
authmub<-na.omit(authmub)
netprodmale<-sum(authmub$prodd[authmub$gender==0])
netprodfemale<-sum(authmub$prodd[authmub$gender==1])
nmaleco=length(unique(authmub$auth[authmub$gender==0]))
nfemaleco=length(unique(authmub$auth[authmub$gender==1]))
x=numeric(length(authmub$articleid))+1
authmub[ , "papers"] <- x
papersmale=length(authmub$auth[authmub$gender==0])
papersfemale=length(authmub$auth[authmub$gender==1])
t=(endyear-authmub$myear)+1
authmub[ , "t"] <- t
ua=unique(authmub[,c(4,5,7)])
tmale=mean(ua$t[ua$gender==0])
tfemale=mean(ua$t[ua$gender==1])
netprodg<-c(netprodmale,netprodfemale, papersmale, papersfemale, nmaleco, nfemaleco, tmale, tfemale)
netprodg
}



